package com.csaba.connector.citi.parser;

import java.io.IOException;
import java.io.Reader;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.StartTag;

import com.csaba.connector.citi.model.CitiRequestFactory;

public class CitiParser
{
	public static String parseNextURL( final String formID, final String formValue, final String attributeName,
			final Reader reader ) throws IOException
	{
		String nextUrl = "";
		final Source source = new Source(reader);
		final StartTag startTag = source.getNextStartTag(0, formID, formValue, true);
		if ( startTag != null )
		{
			final String url = startTag.getAttributeValue(attributeName);
			nextUrl = CitiRequestFactory.HOMEBANK_URL_BASE + url;
		}
		return nextUrl;
	}

	public static String parseNextURL( final Reader reader ) throws IOException
	{
		return parseNextURL("ID", "F1", "action", reader);
	}

	//Error patterns:
	//<TD COLSPAN=3 align=left class="label"> Information not recognised - You may have entered wrong Password or User Name<br><br></TD>
	@SuppressWarnings( "unchecked" )
	public static String parseErrorMsg( final Reader reader ) throws IOException, ParseException
	{
		final Source source = new Source(reader);
		final StringBuilder message = new StringBuilder();

		final List elements = source.getAllElements("class", "label", true);
		for ( final Iterator i = elements.iterator(); i.hasNext(); )
		{
			final Element element = (Element) i.next();
			if ( element.getAllStartTags("a").isEmpty() )
			{
				final String text = element.getTextExtractor().toString();
				if ( !text.isEmpty() )
					message.append(element.getContent() + "\n");
			}
		}

		if ( message.length() == 0 )
		{
			message.append("Unable to parse error message.");
		}

		return message.toString();
	}

}
